package com.king.wxpay.util;

import javax.net.ssl.SSLContext;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 授权证书测试类
 * @author taomk
 * @version 1.0
 * @since 15-7-10 下午4:08
 */
public class ClientCustomSSL {

	public final static void main(String[] args) throws Exception {
		// 1. 指定读取证书格式为PKCS12
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		// 2. 读取本机存放的PKCS12证书文件
		FileInputStream instream = new FileInputStream(new File("/home/taomk/opt/apiclient_cert.p12"));
		try {
			// 3. 指定PKCS12的密码(商户ID)
			keyStore.load(instream, WxConfig.MCH_ID.toCharArray());
		} finally {
			instream.close();
		}

		// Trust own CA and all self-signed certs
		SSLContext sslcontext = SSLContexts.custom()
				.loadKeyMaterial(keyStore, WxConfig.MCH_ID.toCharArray()).build();
		// Allow TLSv1 protocol only
		// 4. 指定TLS版本
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslcontext, new String[]{"TLSv1"}, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		// 5. 设置httpclient的SSLSocketFactory
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();
		try {

			HttpPost httpget = new
					HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");

//			HttpPost httpget = new HttpPost(
//					"https://api.mch.weixin.qq.com/pay/unifiedorder");

			System.out.println("executing request" + httpget.getRequestLine());

			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();

				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());
				if (entity != null) {
					System.out.println("Response content length: " + entity.getContentLength());
					BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
					String text;
					while ((text = bufferedReader.readLine()) != null) {
						System.out.println(text);
					}
				}
				EntityUtils.consume(entity);
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}

}
